#!/bin/bash

# 快速Maxwell验证脚本

echo "=== 快速Maxwell验证脚本 ==="
echo "时间: $(date)"
echo ""

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量
MYSQL_HOST="192.168.10.102"
MYSQL_PORT="3306"
MYSQL_USER="root"
MYSQL_PASSWORD="000000"
MAXWELL_USER="maxwell"
MAXWELL_PASSWORD="maxwell"
DATABASE="smart_tour"
KAFKA_TOPIC="maxwell_smart_tour"
MAXWELL_HOME="/opt/module/maxwell"

# 验证结果
VALIDATION_RESULTS=()

# 验证函数
validate_step() {
    local step_name="$1"
    local command="$2"
    local success_message="$3"
    local failure_message="$4"
    
    echo -e "${BLUE}验证: $step_name${NC}"
    
    if eval "$command" >/dev/null 2>&1; then
        echo -e "${GREEN}✓ $success_message${NC}"
        VALIDATION_RESULTS+=("✓ $step_name")
        return 0
    else
        echo -e "${RED}✗ $failure_message${NC}"
        VALIDATION_RESULTS+=("✗ $step_name")
        return 1
    fi
}

# 1. 验证配置文件
validate_config_file() {
    echo -e "${BLUE}1. 验证配置文件${NC}"
    echo "----------------------------------------"
    
    # 检查配置文件是否存在
    validate_step "配置文件存在" \
        "[ -f '$MAXWELL_HOME/config.properties' ]" \
        "配置文件存在" \
        "配置文件不存在"
    
    # 检查关键配置项
    if [ -f "$MAXWELL_HOME/config.properties" ]; then
        echo "配置文件内容预览:"
        echo "----------------------------------------"
        grep -E "^(host|port|user|password|filter|kafka_topic)=" "$MAXWELL_HOME/config.properties" || echo "未找到关键配置项"
        echo "----------------------------------------"
        
        # 检查过滤规则
        validate_step "过滤规则配置" \
            "grep -q 'filter=include:smart_tour' '$MAXWELL_HOME/config.properties'" \
            "过滤规则配置正确" \
            "过滤规则配置错误或缺失"
    fi
}

# 2. 验证MySQL连接
validate_mysql_connection() {
    echo -e "${BLUE}2. 验证MySQL连接${NC}"
    echo "----------------------------------------"
    
    # 测试root用户连接
    validate_step "Root用户连接" \
        "mysql -h $MYSQL_HOST -P $MYSQL_PORT -u $MYSQL_USER -p$MYSQL_PASSWORD -e 'SELECT 1;'" \
        "Root用户连接正常" \
        "Root用户连接失败"
    
    # 测试maxwell用户连接
    validate_step "Maxwell用户连接" \
        "mysql -h $MYSQL_HOST -P $MYSQL_PORT -u $MAXWELL_USER -p$MAXWELL_PASSWORD -e 'SELECT 1;'" \
        "Maxwell用户连接正常" \
        "Maxwell用户连接失败"
    
    # 测试smart_tour数据库访问
    validate_step "Smart_tour数据库访问" \
        "mysql -h $MYSQL_HOST -P $MYSQL_PORT -u $MAXWELL_USER -p$MAXWELL_PASSWORD -e 'USE $DATABASE; SELECT 1;'" \
        "Smart_tour数据库可访问" \
        "Smart_tour数据库不可访问"
}

# 3. 验证Kafka连接
validate_kafka_connection() {
    echo -e "${BLUE}3. 验证Kafka连接${NC}"
    echo "----------------------------------------"
    
    # 检查kafka-topics命令
    validate_step "Kafka工具可用" \
        "command -v kafka-topics.sh" \
        "Kafka工具可用" \
        "Kafka工具不可用"
    
    if command -v kafka-topics.sh >/dev/null 2>&1; then
        # 检查Kafka服务
        validate_step "Kafka服务连接" \
            "kafka-topics.sh --bootstrap-server hadoop102:9092 --list >/dev/null 2>&1" \
            "Kafka服务连接正常" \
            "Kafka服务连接失败"
        
        # 检查主题是否存在
        validate_step "Kafka主题存在" \
            "kafka-topics.sh --bootstrap-server hadoop102:9092 --list 2>/dev/null | grep -q '$KAFKA_TOPIC'" \
            "Kafka主题存在" \
            "Kafka主题不存在"
    fi
}

# 4. 验证Maxwell进程
validate_maxwell_process() {
    echo -e "${BLUE}4. 验证Maxwell进程${NC}"
    echo "----------------------------------------"
    
    # 检查Maxwell进程
    validate_step "Maxwell进程运行" \
        "ps aux | grep maxwell | grep -v grep" \
        "Maxwell进程正在运行" \
        "Maxwell进程未运行"
    
    # 检查Maxwell日志
    if [ -f "$MAXWELL_HOME/logs/maxwell.log" ]; then
        echo "Maxwell日志最后5行:"
        echo "----------------------------------------"
        tail -5 "$MAXWELL_HOME/logs/maxwell.log"
        echo "----------------------------------------"
        
        # 检查错误日志
        validate_step "Maxwell日志无错误" \
            "! grep -i error '$MAXWELL_HOME/logs/maxwell.log' | tail -1" \
            "Maxwell日志无错误" \
            "Maxwell日志有错误"
    else
        echo -e "${YELLOW}⚠ Maxwell日志文件不存在${NC}"
    fi
}

# 5. 验证数据库环境
validate_database_environment() {
    echo -e "${BLUE}5. 验证数据库环境${NC}"
    echo "----------------------------------------"
    
    # 检查smart_tour数据库是否存在
    validate_step "Smart_tour数据库存在" \
        "mysql -h $MYSQL_HOST -P $MYSQL_PORT -u $MYSQL_USER -p$MYSQL_PASSWORD -e 'USE $DATABASE; SELECT 1;'" \
        "Smart_tour数据库存在" \
        "Smart_tour数据库不存在"
    
    # 检查binlog状态
    validate_step "Binlog已开启" \
        "mysql -h $MYSQL_HOST -P $MYSQL_PORT -u $MYSQL_USER -p$MYSQL_PASSWORD -e 'SHOW VARIABLES LIKE \"log_bin\";' | grep -q 'ON'" \
        "Binlog已开启" \
        "Binlog未开启"
}

# 6. 验证权限
validate_permissions() {
    echo -e "${BLUE}6. 验证权限${NC}"
    echo "----------------------------------------"
    
    # 检查maxwell用户权限
    echo "Maxwell用户权限:"
    mysql -h $MYSQL_HOST -P $MYSQL_PORT -u $MYSQL_USER -p$MYSQL_PASSWORD -e "SHOW GRANTS FOR 'maxwell'@'%';" 2>/dev/null || echo "无法获取权限信息"
    
    # 检查必要权限
    validate_step "SELECT权限" \
        "mysql -h $MYSQL_HOST -P $MYSQL_PORT -u $MAXWELL_USER -p$MAXWELL_PASSWORD -e 'SELECT 1;'" \
        "SELECT权限正常" \
        "SELECT权限不足"
    
    validate_step "REPLICATION SLAVE权限" \
        "mysql -h $MYSQL_HOST -P $MYSQL_PORT -u $MAXWELL_USER -p$MAXWELL_PASSWORD -e 'SHOW MASTER STATUS;'" \
        "REPLICATION SLAVE权限正常" \
        "REPLICATION SLAVE权限不足"
}

# 7. 功能测试
test_functionality() {
    echo -e "${BLUE}7. 功能测试${NC}"
    echo "----------------------------------------"
    
    echo "创建测试表..."
    mysql -h $MYSQL_HOST -P $MYSQL_PORT -u $MYSQL_USER -p$MYSQL_PASSWORD << EOF
USE $DATABASE;
CREATE TABLE IF NOT EXISTS maxwell_validation_test (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    value TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
EOF
    
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ 测试表创建成功${NC}"
        
        # 执行测试操作
        echo "执行测试操作..."
        mysql -h $MYSQL_HOST -P $MYSQL_PORT -u $MYSQL_USER -p$MYSQL_PASSWORD << EOF
USE $DATABASE;
INSERT INTO maxwell_validation_test (name, value) VALUES ('验证测试', '这是验证测试数据');
UPDATE maxwell_validation_test SET value = '这是更新后的验证测试数据' WHERE name = '验证测试';
DELETE FROM maxwell_validation_test WHERE name = '验证测试';
EOF
        
        if [ $? -eq 0 ]; then
            echo -e "${GREEN}✓ 测试操作执行成功${NC}"
            VALIDATION_RESULTS+=("✓ 功能测试")
        else
            echo -e "${RED}✗ 测试操作执行失败${NC}"
            VALIDATION_RESULTS+=("✗ 功能测试")
        fi
    else
        echo -e "${RED}✗ 测试表创建失败${NC}"
        VALIDATION_RESULTS+=("✗ 功能测试")
    fi
}

# 8. 显示验证结果
show_validation_results() {
    echo -e "${BLUE}8. 验证结果总结${NC}"
    echo "----------------------------------------"
    
    local passed=0
    local failed=0
    
    for result in "${VALIDATION_RESULTS[@]}"; do
        if [[ $result == ✓* ]]; then
            echo -e "${GREEN}$result${NC}"
            ((passed++))
        else
            echo -e "${RED}$result${NC}"
            ((failed++))
        fi
    done
    
    echo ""
    echo "验证统计:"
    echo -e "${GREEN}通过: $passed${NC}"
    echo -e "${RED}失败: $failed${NC}"
    
    if [ $failed -eq 0 ]; then
        echo -e "${GREEN}🎉 所有验证项目通过！Maxwell配置正确。${NC}"
    else
        echo -e "${RED}⚠ 有 $failed 个验证项目失败，请检查配置。${NC}"
    fi
}

# 9. 提供修复建议
provide_fix_suggestions() {
    echo -e "${BLUE}9. 修复建议${NC}"
    echo "----------------------------------------"
    
    echo "如果验证失败，请按以下步骤修复："
    echo ""
    echo "1. 配置文件问题："
    echo "   - 检查配置文件路径: $MAXWELL_HOME/config.properties"
    echo "   - 确保包含过滤规则: filter=include:smart_tour.*"
    echo ""
    echo "2. MySQL连接问题："
    echo "   - 检查MySQL服务状态: systemctl status mysqld"
    echo "   - 检查maxwell用户权限"
    echo "   - 确保smart_tour数据库存在"
    echo ""
    echo "3. Kafka连接问题："
    echo "   - 检查Kafka服务状态: jps | grep Kafka"
    echo "   - 创建主题: kafka-topics.sh --bootstrap-server hadoop102:9092 --create --topic $KAFKA_TOPIC"
    echo ""
    echo "4. Maxwell进程问题："
    echo "   - 启动Maxwell: /opt/module/maxwell/bin/maxwell --config=$MAXWELL_HOME/config.properties"
    echo "   - 检查日志: tail -f $MAXWELL_HOME/logs/maxwell.log"
    echo ""
    echo "5. 权限问题："
    echo "   - 授予权限: GRANT SELECT, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'maxwell'@'%';"
    echo "   - 刷新权限: FLUSH PRIVILEGES;"
}

# 主函数
main() {
    case "$1" in
        "config")
            validate_config_file
            ;;
        "connection")
            validate_mysql_connection
            validate_kafka_connection
            ;;
        "process")
            validate_maxwell_process
            ;;
        "permissions")
            validate_permissions
            ;;
        "test")
            test_functionality
            ;;
        "all"|"")
            validate_config_file
            validate_mysql_connection
            validate_kafka_connection
            validate_maxwell_process
            validate_database_environment
            validate_permissions
            test_functionality
            ;;
        *)
            echo "使用方法: $0 {all|config|connection|process|permissions|test}"
            echo ""
            echo "命令说明:"
            echo "  all         - 执行所有验证"
            echo "  config      - 验证配置文件"
            echo "  connection  - 验证连接"
            echo "  process     - 验证进程"
            echo "  permissions - 验证权限"
            echo "  test        - 功能测试"
            ;;
    esac
    
    show_validation_results
    provide_fix_suggestions
}

# 执行主函数
main "$@" 